﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using RecommenderSystem.misc;


namespace RecommenderSystem.algorithms.itemBased
{
    class CP : ItemBased
    {
        private Cache cpCache;
        public readonly string ALGORITHM_NAME = "CP";
        public CP(Dictionary<string, User> users, ICollection<IDataRecord> dataset, Dictionary<string, Cache> cache)
            : base(users, dataset)
        {
            if (!cache.ContainsKey(ALGORITHM_NAME))
                cache.Add(ALGORITHM_NAME, new Cache());

            cpCache = cache[ALGORITHM_NAME];
        }

        public override double predictRating(string userID, string itemID)
        {
            double answer = 0d;
            if (!_users.ContainsKey(userID))
            {
//                logger.Warn("Ilegal User: "+ userID);
                return answer;
            }

            var allMyItems = _users[userID].getRatedItemsIds();
            double prediction;
            foreach (String myRatedItem in allMyItems)
            {
                prediction = calculateConditionalProbability(itemID, myRatedItem);
                if (prediction > answer)
                {
                    answer = prediction;
                }
            }
            return answer;
        }

        /**
         * Calculates conditional probability =  P(item1 | item2)
         */ 
        private double calculateConditionalProbability(string item1, string item2)
        {
            double usedBothItems = 0, usedItem1 = 0, usedItem2= 0;

            if (cpCache.isCached(item1, item2))
            {
                return cpCache.retrieveFromCache(item1, item2);
            }

            foreach (User user in _users.Values)
            {
                if (user.getItemRate(item1) != -1 && user.getItemRate(item2) != -1)
                {
                    usedBothItems++;
                    usedItem1++;
                    usedItem2++;

                }else if (user.getItemRate(item1) != -1)
                        usedItem1++;
                    else if (user.getItemRate(item2) != -1)
                        usedItem2++;
                            
            }

            cpCache.addToCache(item1, item2, usedBothItems < Config.CP_THRESHOLD ? 0 : usedBothItems / usedItem2);
            cpCache.addToCache(item2, item1, usedBothItems < Config.CP_THRESHOLD ? 0 : usedBothItems / usedItem1);
            
            return cpCache.retrieveFromCache(item1, item2);
        }
    }
}
